package com.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.demo.mapper.UserItem2Mapper;
import com.demo.mapper.UserItemMapper;
import com.demo.model.UserItem;
import com.demo.model.UserItem2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiuYuanQi
 * @Date: 2020/4/15 10:20
 */

@Service
public class DataService {

    @Autowired
    private UserItemMapper userItemMapper;
    @Autowired
    private UserItem2Mapper userItem2Mapper;

    public List<UserItem> initUserItem(){
        int[][] initArgs={
                {3,1,4,4,1,0,0},
                {0,5,1,0,0,4,0},
                {1,0,5,4,3,5,2},
                {3,1,4,3,5,0,0},
                {5,2,0,1,0,5,5}
        };
        List<UserItem> UserItems = new ArrayList();
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 7; j++) {
                if (initArgs[i][j]>0) {
                    UserItems.add(UserItem.builder().userId(i).itemId(j).likeOf(initArgs[i][j]).build());
                }
            }
        }
        userItemMapper.initData(UserItems);
        return UserItems;
    }

    public String initBatchData(){
        File file = new File("d:\\ratings.data");
        List<UserItem2> UserItem2s = new ArrayList();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                String[] line = s.split(",");
                Integer userId = Integer.parseInt(line[0]);
                Integer itemId = Integer.parseInt(line[1]);
                Double likeOf = Double.parseDouble(line[2]);
                Integer createTime = Integer.parseInt(line[3]);
                UserItem2s.add(UserItem2.builder().userId(userId).itemId(itemId).likeOf(likeOf).createTime(createTime).build());
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        userItem2Mapper.initBatchData(UserItem2s);
        return JSONObject.toJSONString(UserItem2s);
    }

}